package main

import (
	lib "im/libs"
	"im/model"
	protos "im/pb"
	"net"
)


var users map[string]string = map[string]string{
	"admin": "123",
	"abc":   "123",
	"def":   "123",
}

var uids map[string]uint64 = map[string]uint64{
	"admin": 123,
	"abc":   125,
	"def":   210,
}

var t *model.Token

func do_auth(conn net.Conn, req *protos.Request) {
	r := &protos.Response{Command: protos.Command_AUTH}
	addr := conn.RemoteAddr().String()
	var err error
	r.Token, err = t.Gen(uids[req.Username], addr)
	if err !=nil {
		r := &protos.Response{Command: protos.Command_SEND_MSG,Errcode: protos.ErrCode_SERVER_ERR,Errmsg:err.Error()}
		rsp, _ := lib.EncodeRsp(r)
		conn.Write(rsp)
		return
	}
	rsp, err := lib.EncodeRsp(r)
	if err !=nil {
		r := &protos.Response{Command: protos.Command_SEND_MSG,Errcode: protos.ErrCode_SERVER_ERR,Errmsg:err.Error()}
		rsp, _ := lib.EncodeRsp(r)
		conn.Write(rsp)
		return
	}
	conn.Write(rsp)
}

func authHandle(t *(lib.Task)) {
	defer t.Client.Close()
	for {
		req, err := lib.ReadReq(t.Client)
		if err != nil {
			break
		}
		switch req.Command {
		case protos.Command_AUTH:
			if users[req.Username] == req.Password {
				do_auth(t.Client, req)
			} else {
				r := &protos.Response{Command: protos.Command_SEND_MSG,Errcode: protos.ErrCode_SERVER_ERR}
				rsp, _ := lib.EncodeRsp(r)
				t.Client.Write(rsp)
			}
		default:
			r := &protos.Response{Command: protos.Command_SEND_MSG,Errcode: protos.ErrCode_SERVER_ERR}
			rsp, _ := lib.EncodeRsp(r)
			t.Client.Write(rsp)
		}

	}

}

func main() {
	redis, err := lib.NewRedisConfig("./config")
	if err != nil {
		panic("redis config load failed.")
	}
	if r, e := redis.Servers["user"]; e {
		t, err = model.NewToken(&r)
		if err != nil {
			panic("redis config connect failed.")
		}
		s, _ := lib.NewServer("127.0.0.1", 1001, 10, authHandle)
		s.Start()
	} else {
		panic("redis config load failed.")
	}

}
